<template>
	<view>
		<cu-custom bgColor="bg-gradual-fff" isBack="true">
			<block slot="content">创建商品</block>
		</cu-custom>

		<u-loading-page :loading="showLoading" loading-text="加载中..." v-if="showLoading"></u-loading-page>

		<view v-show="!showLoading" class="create-goods-container">
			<!-- 商品基本信息 -->
			<view class="form-section">
				<view class="form-item">
					<text class="form-label">商品名称</text>
					<u-input v-model="addForm.name" placeholder="请输入商品名称" border="bottom"></u-input>
				</view>

				<view class="form-item">
					<text class="form-label">商品分类</text>
					<u-button @click="showCategoryPopup = true" plain>
						{{ addForm.categoryId ? selectedCategoryName : '请选择分类' }}
					</u-button>
				</view>

				<view class="form-item">
					<text class="form-label">销售价格</text>
					<u-input v-model="addForm.price" placeholder="请输入销售价格" type="number" border="bottom">
						<template #suffix>
							<text>积分</text>
						</template>
					</u-input>
				</view>

				<view class="form-item">
					<text class="form-label">原价</text>
					<u-input v-model="addForm.originalPrice" placeholder="请输入原价" type="number" border="bottom">
						<template #suffix>
							<text>积分</text>
						</template>
					</u-input>
				</view>
			</view>

			<!-- 商品图片 -->
			<view class="form-section">
				<view class="form-item">
					<text class="form-label">商品主图</text>
					<u-upload :fileList="mainImageList" @afterRead="handleMainImageUpload" @delete="deleteMainImage"
						:maxCount="1" :previewFullImage="true"></u-upload>
				</view>
			</view>

			<!-- 商品描述 -->
			<view class="form-section">
				<view class="form-item">
					<text class="form-label">商品描述</text>
					<u-textarea v-model="addForm.description" placeholder="请输入商品详细描述" height="200"></u-textarea>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-btn">
				<u-button type="primary" @click="submitGoods" :loading="submitting">创建商品</u-button>
			</view>
		</view>

		<!-- 分类选择弹窗 -->
		<u-popup :show="showCategoryPopup" mode="bottom" round="16" @close="showCategoryPopup = false">
			<view class="category-popup">
				<view class="popup-header">
					<text class="popup-title">选择分类</text>
					<u-icon name="close" @click="showCategoryPopup = false"></u-icon>
				</view>

				<scroll-view scroll-y class="category-list">
					<view v-for="category in categories" :key="category.id" class="category-item"
						:class="{active: addForm.categoryId === category.id}" @click="selectCategory(category)">
						<text>{{ category.name }}</text>
						<u-icon v-if="addForm.categoryId === category.id" name="checkmark" color="#19BE6B"></u-icon>
					</view>
				</scroll-view>

				<view class="popup-footer">
					<u-button type="primary" @click="confirmCategory">确定</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import api from '../../common/apiService';
	import request from '../../common/request';

	export default {
		data() {
			return {
				showLoading: false,
				submitting: false,
				showCategoryPopup: false,
				categories: [],
				selectedCategoryName: '',
				mainImageList: [],
				addForm: {
					name: '',
					categoryId: '',
					price: null,
					originalPrice: null,
					sellerId: 0,
					image: '',
					description: '',
					status: 1
				},
				uploadUrl: request.baseUrl + 'api/file/upload'
			}
		},
		onLoad() {
			this.addForm.sellerId = uni.getStorageSync('mid');
			this.fetchCategories();
		},
		methods: {
			async fetchCategories() {
				this.showLoading = true;
				try {
					const res = await request.httpRequest({
						url: 'api/category/enabled',
						method: 'get'
					});

					if (res.data.code === 200) {
						this.categories = res.data.data;
					}
				} catch (error) {
					console.error('获取分类失败:', error);
					uni.showToast({
						title: '获取分类失败',
						icon: 'none'
					});
				} finally {
					this.showLoading = false;
				}
			},

			selectCategory(category) {
				this.addForm.categoryId = category.id;
				this.selectedCategoryName = category.name;
			},

			confirmCategory() {
				if (!this.addForm.categoryId) {
					uni.showToast({
						title: '请选择分类',
						icon: 'none'
					});
					return;
				}
				this.showCategoryPopup = false;
			},

			// 处理主图上传
			async handleMainImageUpload(event) {
				const file = event.file;
				this.mainImageList = [{
					...file
				}];

				try {
					const imgUrl = await this.uploadFilePromise(file.url, this.uploadUrl, 'main');
					this.mainImageList[0].message = '';
					this.mainImageList[0].url = imgUrl;
					console.log("上传后", imgUrl)
				} catch (error) {
				}
			},

			// 删除主图
			deleteMainImage() {
				this.mainImageList = [];
				this.addForm.image = '';
			},
			uploadFilePromise(url, uploadUrl, type) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: uploadUrl,
						filePath: url,
						name: "file",
						formData: {
							user: "test",
						},
						success: (res) => {
							setTimeout(() => {
								try {
									const result = JSON.parse(res.data);
									this.addForm.image = result.data.url;

									console.log("得到", result)
									if (result.url) {
										resolve(result.url);
									} else {
										reject(new Error('未获取到图片URL'));
									}
								} catch (e) {
									reject(new Error('解析响应失败'));
								}
							}, 1000);
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},

			async submitGoods() {
			    if (!this.addForm.name) {
			        uni.showToast({
			            title: '请输入商品名称',
			            icon: 'none'
			        });
			        return;
			    }
			
			    if (!this.addForm.categoryId) {
			        uni.showToast({
			            title: '请选择商品分类',
			            icon: 'none'
			        });
			        return;
			    }
			
			    if (!this.addForm.price) {
			        uni.showToast({
			            title: '请输入销售价格',
			            icon: 'none'
			        });
			        return;
			    }
			
			    if (!this.addForm.image) {
			        uni.showToast({
			            title: '请上传商品主图',
			            icon: 'none'
			        });
			        return;
			    }
			
			    this.submitting = true;
			
			    try {
			        const formData = {
			            ...this.addForm,
			            price: parseInt(this.addForm.price),
			            originalPrice: this.addForm.originalPrice ? parseInt(this.addForm.originalPrice) : undefined
			        };
					
			
			        console.log("创建", formData)
			        const res = await request.httpRequest({
			            url: 'api/goods',
			            method: 'post',
			        },this.addForm );
			
			        if (res.data.code === 200) {
			            uni.showToast({
			                title: '商品创建成功'
			            });
			            setTimeout(() => {
			                uni.navigateBack();
			            }, 1500);
			        } else {
			            uni.showToast({
			                title: res.data.msg || '创建失败',
			                icon: 'none'
			            });
			        }
			    } catch (error) {
			        console.error('创建商品失败:', error);
			        uni.showToast({
			            title: '创建商品失败',
			            icon: 'none'
			        });
			    } finally {
			        this.submitting = false;
			    }
			}
		}
	}
</script>

<style lang="scss" scoped>
	.create-goods-container {
		padding: 30rpx;
	}

	.form-section {
		background: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.form-item {
		margin-bottom: 40rpx;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.form-label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		font-weight: bold;
	}

	.submit-btn {
		margin-top: 60rpx;
		padding: 0 30rpx;
	}

	/* 分类弹窗样式 */
	.category-popup {
		padding: 30rpx;
		max-height: 70vh;
		display: flex;
		flex-direction: column;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;

		.popup-title {
			font-size: 32rpx;
			font-weight: bold;
		}
	}

	.category-list {
		flex: 1;
		margin-bottom: 30rpx;
		max-height: 50vh;
	}

	.category-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 0;
		border-bottom: 1rpx solid #f5f5f5;

		&.active {
			color: #19BE6B;
		}
	}

	.popup-footer {
		padding-top: 20rpx;
		border-top: 1rpx solid #f5f5f5;
	}

	/* 调整uView组件样式 */
	/deep/ .u-upload__wrap {
		margin-top: 10rpx;
	}

	/deep/ .u-textarea {
		background: #f8f8f8;
		border-radius: 12rpx;
		padding: 20rpx;
	}
</style>